package com.cisystem.system.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import com.cisystem.common.core.domain.entity.SysUser;
import com.cisystem.common.exception.ServiceException;
import com.cisystem.common.utils.DateUtils;
import com.cisystem.common.utils.SecurityUtils;
import com.cisystem.common.utils.StringUtils;
import com.cisystem.common.utils.bean.BeanValidators;
import com.cisystem.system.domain.vo.GoodCatchVo;
import com.cisystem.system.mapper.SysUserMapper;
import com.cisystem.system.mapper.SysUserRoleMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cisystem.system.mapper.GoodCatchMapper;
import com.cisystem.system.domain.GoodCatch;
import com.cisystem.system.service.IGoodCatchService;

import javax.validation.Validator;

/**
 * GoodCatchService业务层处理
 *
 * @author kelly
 * @date 2023-07-08
 */
@Service

public class GoodCatchServiceImpl implements IGoodCatchService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);
    @Autowired
    private GoodCatchMapper goodCatchMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    protected Validator validator;

    @Autowired
    private MailSendServiceImpl mailSendService;

    /**
     * 查询GoodCatch
     *
     * @param id GoodCatch主键
     * @return GoodCatch
     */
    @Override
    public GoodCatch selectGoodCatchById(Long id) {
        return goodCatchMapper.selectGoodCatchById(id);
    }

    /**
     * 查询GoodCatch列表
     *
     * @param goodCatch GoodCatch
     * @return GoodCatch
     */
    @Override
    public List<GoodCatch> selectGoodCatchList(GoodCatch goodCatch) {
        return goodCatchMapper.selectGoodCatchList(goodCatch);
    }

    /**
     * 新增GoodCatch
     *
     * @param goodCatchVo GoodCatch
     * @return 结果
     */
    @Override
    public int insertGoodCatch(GoodCatchVo goodCatchVo) {
        GoodCatch goodCatch1 = new GoodCatch();
        goodCatch1.setDescription(goodCatchVo.getDescription());
        List<GoodCatch> goodCatches = goodCatchMapper.selectGoodCatchList(goodCatch1);
        if(goodCatches != null && goodCatches.size() > 0){
            return 0;
        }
        if (goodCatchVo.getIsSendMail()) {

            // add good catch send mail
            mailSendService.sendMailByAddGoodCatch(goodCatchVo);

            /*MailAccount mailAccount = new MailAccount().setFrom("xing.zhou@ovt.com").setAuth(true)
                    .setUser("xing.zhou").setPass("Shanshan05201")
                    .setHost("10.0.0.198").setPort(25);

            String msg = MailUtil.send(mailAccount, "xing.zhou@ovt.com", "主题", "<h1 style='color:red'>test content</h1>", true);
            System.out.println("mail send result:" + msg);*/

        }

        return goodCatchMapper.insertGoodCatch(goodCatchVo);
    }

    /**
     * 修改GoodCatch
     *
     * @param goodCatchVo GoodCatchVo
     * @return 结果
     */
    @Override
    public int updateGoodCatch(GoodCatchVo goodCatchVo) {

        if (goodCatchVo.getIsSendMail()) {


            // update good catch send mail

            mailSendService.sendMailByUpdateGoodCatch(goodCatchVo);

            /*List<String> toMails=new ArrayList<>();
            List<String> ccMails=new ArrayList<>();
            ccMails.add("kelly.gu@ovt.com");
            //获取 owner 人员信息
            SysUser ownerUser = sysUserMapper.selectUserByEmployeeId(goodCatchVo.getOwnerId());
            if (ownerUser != null && StrUtil.isNotEmpty(ownerUser.getEmail()) ){
                toMails.add(ownerUser.getEmail());
            }
            MailAccount mailAccount = new MailAccount().setFrom("xing.zhou@ovt.com").setAuth(true)
                    .setUser("xing.zhou").setPass("Shanshan05201")
                    .setHost("10.0.0.198").setPort(25);

            if(CollUtil.isNotEmpty(toMails)){
                String msg = MailUtil.send(mailAccount, toMails,ccMails,null, "主题", "<h1 style='color:red'>test content</h1>", true);
                System.out.println("msg:"+msg);
            }*/
        }

        return goodCatchMapper.updateGoodCatch(goodCatchVo);
    }

    /**
     * 批量删除GoodCatch
     *
     * @param ids 需要删除的GoodCatch主键
     * @return 结果
     */
    @Override
    public int deleteGoodCatchByIds(Long[] ids) {
        return goodCatchMapper.deleteGoodCatchByIds(ids);
    }

    @Override
    public int reClosedGoodCatchByIds(Long[] ids) {
        return  goodCatchMapper.reClosedGoodCatchByIds(ids);
    }

    /**
     * 删除GoodCatch信息
     *
     * @param id GoodCatch主键
     * @return 结果
     */
    @Override
    public int deleteGoodCatchById(Long id) {
        return goodCatchMapper.deleteGoodCatchById(id);
    }

    @Override
    public String importGoodCatch(List<GoodCatch> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (GoodCatch goodCatch : userList) {
            try {
                // 验证是否存在这个用户
                GoodCatch u = goodCatchMapper.selectGoodCatchById(goodCatch.getId());
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, goodCatch);
                    goodCatch.setCreateBy(operName);
                    goodCatchMapper.insertGoodCatch(goodCatch);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "ID:" + goodCatch.getId() + ",Title:" + goodCatch.getTitle() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, goodCatch);
                    goodCatch.setUpdateBy(operName);
                    goodCatchMapper.updateGoodCatch(goodCatch);
                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("ID:").append(goodCatch.getId()).append(",Title:").append(goodCatch.getTitle()).append(" 更新成功");
                } else {
                    failureNum++;
                    successMsg.append("<br/>").append(successNum).append("ID:").append(goodCatch.getId()).append(",Title:").append(goodCatch.getTitle()).append(" 已经存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + successNum + "ID:" + goodCatch.getId() + ",Title:" + goodCatch.getTitle() + " 导入成功";
                failureMsg.append(msg).append(e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    public  void overdueHandler(){
        //select * from ci_good_catch where status!=3 and due_date<now()
        List<GoodCatch> goodCatches = goodCatchMapper.selectOverdueGoodCatchList();
        for (GoodCatch goodCatch:goodCatches ){
            if( goodCatch.getDueDate().getTime() > DateUtils.getNowDate().getTime()){
                continue;
            }
            mailSendService.sendMailByOverdueGoodCatch(goodCatch);
        }
    }

}